package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"sync"

	"./Robot"

	"./Achieve"
	"./ClientCMD"
	"./Common"
	"./Item"
	"./Login"
	"./Overseas"
	"./SceneUser2"
)

type GobalConfig struct {
	ProxyIP   string `json:"proxyIP"`
	ProxyPort int    `json:"proxyPort"`
	ZoneId    uint32 `json:"zoneId"`
}
type RobotConfig struct {
	Accid       uint64  `json:accid`
	LogicModule []int32 `json:logicModule`
}
type RoRobotConfig struct {
	Global GobalConfig   `json:global`
	Robots []RobotConfig `json:robots`
}

func initLog() error {
	file, err := os.OpenFile("RoRobot.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Println(err)
		return err
	}

	log.SetOutput(file)
	log.Println("=============new start=============")
	return nil
}

func readJson(config *RoRobotConfig) error {
	//读取配置文件
	file, err := os.Open("RoRobotConfig.json")
	if err != nil {
		log.Println(err)
		return err
	}
	//解析json
	jsonBytes, err := ioutil.ReadAll(file)
	if err != nil {
		log.Println(err)
		return err
	}

	err = json.Unmarshal(jsonBytes, config)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

//RegisterModule 注册需要处理模块
func RegisterModule(robot *Robot.Robot, moduleArr []int32) {

	if robot.Handler == nil {
		robot.Handler = Robot.NewRobotHandler(robot)
	}

	for idx := 0; idx < len(moduleArr); idx++ {
		switch moduleArr[idx] {
		case 1:
			LoginHandler.RegisterLoginHandler(robot)
		case 2:
			Common.RegisterErrorHandler(robot)
		case 6:
			Item.RegisterItemHandler(robot)
		case 9:
			SceneUser2.RegisterSceneUser2Handler(robot)
		case 17:
			Achieve.RegisterAchieveHandler(robot)
		case 81:
			Overseas.RegisterOverseasHandler(robot)
		case 99:
			Client.RegisterClientHandler(robot)
		default:
			log.Println("还没实现模块 ", moduleArr[idx])
		}
	}

}

func main() {
	if err := initLog(); err != nil {
		fmt.Println("初始化log错误 ", err)
		return
	}

	config := &RoRobotConfig{}

	if err := readJson(config); err != nil {
		fmt.Println("读取json错误 ", err)
		return
	}

	var waitG sync.WaitGroup
	waitG.Add(len(config.Robots))

	for idx := 0; idx < len(config.Robots); idx++ {
		accinfo := Robot.RobotAccount{Accid: config.Robots[idx].Accid,
			Zoneid: config.Global.ZoneId,
			Addr:   config.Global.ProxyIP,
			Port:   config.Global.ProxyPort}

		rb := Robot.NewRobot(accinfo, &waitG)
		RegisterModule(rb, config.Robots[idx].LogicModule)
		go rb.Loop()
	}
	//等待所有机器人完成
	waitG.Wait()
	log.Println("MISSION COMPLETED")
}
